package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService; // 秒杀优惠券服务
    @Autowired
    private RedisWorker redisWorker; // Redis工具类
    @Autowired
    private StringRedisTemplate stringRedisTemplate; // Redis操作模板
    @Autowired
    private RedissonClient redissonClient; // Redisson客户端
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT; // Lua脚本对象
    private static final ExecutorService executor = Executors.newSingleThreadExecutor(); // 单线程线程池

    // 初始化方法，启动订单处理线程
    @PostConstruct
    public void init(){
        executor.submit(new VoucherOrderHandler());
    }

    // 订单处理线程类
    private class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    // 从Redis Stream中读取订单数据
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"), // 消费者组和消费者
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)), // 读取配置
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed()) // 读取偏移量
                    );
                    if (read == null || read.isEmpty()){
                        continue; // 如果没有数据，继续循环
                    }
                    // 获取第一条记录
                    MapRecord<String, Object, Object> record = read.get(0);
                    Map<Object, Object> values = record.getValue();
                    // 将Redis中的数据映射为VoucherOrder对象
                    VoucherOrder voucherOrder = new VoucherOrder();
                    BeanUtil.fillBeanWithMap(values, voucherOrder, true);
                    // 处理订单
                    handleVoucherOrder(voucherOrder);
                    // 确认消息已被处理
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1", record.getId());
                } catch (Exception e) {
                    // 如果发生异常，处理未确认的消息
                    handlePendingList();
                }
            }
        }
    }

    // 处理未确认的消息
    private void handlePendingList() {
        while (true) {
            try {
                // 从Redis Stream中读取未确认的消息
                List<MapRecord<String, Object, Object>> pendingList = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"), // 消费者组和消费者
                        StreamReadOptions.empty().count(1), // 读取配置
                        StreamOffset.create("stream.orders", ReadOffset.from("0")) // 从起始位置读取
                );
                if (pendingList == null || pendingList.isEmpty()) {
                    break; // 如果没有数据，退出循环
                }
                // 获取第一条记录
                MapRecord<String, Object, Object> record = pendingList.get(0);
                Map<Object, Object> values = record.getValue();
                // 将Redis中的数据映射为VoucherOrder对象
                VoucherOrder voucherOrder = new VoucherOrder();
                BeanUtil.fillBeanWithMap(values, voucherOrder, true);
                // 处理订单
                handleVoucherOrder(voucherOrder);
                // 确认消息已被处理
                stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理订单异常", e);
                try {
                    Thread.sleep(50); // 发生异常时，等待50ms后重试
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    // 处理订单的通用方法
    public void handleVoucherOrder(VoucherOrder voucherOrder) {
        save(voucherOrder); // 保存订单到数据库
    }

    // 静态代码块，初始化Lua脚本
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua")); // 加载Lua脚本文件
        SECKILL_SCRIPT.setResultType(Long.class); // 设置脚本返回类型
    }

    // 秒杀优惠券方法
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId(); // 获取当前用户ID
        Long orderId = redisWorker.nextId("order"); // 生成订单ID
        // 执行Lua脚本，进行秒杀操作
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), // 优惠券ID
                userId.toString(), // 用户ID
                orderId.toString()); // 订单ID
        // 根据脚本返回值返回结果
        return result  == 0 ? Result.ok(orderId) : Result.fail(result == 1 ? "库存不足" : "不能重复下单");
    }
}